<template>
  <div id="app">
    <router-view></router-view>
  </div>
</template>

<script>
import baseURL from "@/common/baseUrl.js";
import { mapState } from "vuex"
export default {
  data(){
    return{
      webSocket: null,
      timer: null,
      lockReconnect: false,
    }
  },

  created(){
    console.log(baseURL.name)
    let token = window.localStorage.getItem("ai_token") || ""
    if(!token) return this.$router.push({name: "index"})
    this.$store.dispatch("getUser")
    if(this.timer) {
      clearInterval(this.timer)
      this.timer = null
    }
    if(this.webSocket) this.webSocket.close()
    this.initwebsocket()
  },

  computed: {
    ...mapState({
      statusRandom: state=> state.statusRandom,
      currentChat: state=> state.currentChat,
      currentWeChat: state=> state.currentWeChat,
    })
  },
  
  mounted(){
    window.addEventListener("offline", ()=>{
      console.log("已断网"); //网络由正常到异常时触发
      this.$message({
        showClose: true,
        message: "抱歉，当前网络信号不稳定，请检查网络状态后重试",
        type: 'warning',
        duration: 0
      })
    })
    window.addEventListener("online", ()=>{
      console.log("网络已连接"); // 网络由异常到正常时触发
    })
  },

  watch: {
    statusRandom(){
      if(this.statusRandom==1) {
        this.initwebsocket()
      }
      if(this.statusRandom==-1){
        if(this.timer) {
          clearInterval(this.timer)
          this.timer = null
        }
        this.webSocket.close()
      } 
    }
  },

  methods: {
    initwebsocket() {
      if (this.lockReconnect) return
      let token = window.localStorage.getItem("ai_token")
      this.webSocket = new WebSocket(`${baseURL.socketUrl}?token=${token}`);
      this.webSocket.onopen = this.webSocketOnopen  //连接建立成功
      this.webSocket.onmessage = this.webSocketOnMessage  //接受数据 
      this.webSocket.onerror = this.webSocketOnError   //连接建立失败 
      this.webSocket.onclose = this.webSocketOnClose   //连接关闭
    },

    webSocketOnopen(){ 
      console.log("webSocket初始化完成")
      this.lockReconnect = false
      this.timer = setInterval(() => {
        if(this.webSocket.readyState!=1) {
          clearInterval(this.timer)
          this.timer = null
        }
        this.webSocket.send("PING")
      }, 2000)  
    },

    webSocketOnError(){
      this.lockReconnect = false
      console.log('监控WebSocket连接发生错误')
    },

    webSocketOnClose(){
      this.lockReconnect = false
      console.log("监控webSocket连接关闭"); 
      clearInterval(this.timer)
      this.timer = null
      this.webSocket.close();
      this.lockReconnect = false;
      this.reconnect();
    },

    reconnect(){
      console.log("重连ws", this.lockReconnect)
      if(this.lockReconnect) return
      this.lockReconnect = true
      setTimeout(() => {
        this.lockReconnect = false;
        this.initwebsocket()
      }, 2000);
    },

    webSocketOnMessage(e){
      const data = JSON.parse(e.data);
      // console.log("接收的消息=>", data)
      if(data.status==="loginout") {
        console.log("监控到微信退出登录")
        setTimeout(() => {
          this.$store.state.loginoutRandom = Math.random()
        }, 1000); 
      }

      // 收到消息
      if(data.lastMessage) {
        // if(data.type===0) console.log("收到私聊消息", data.id, data, this.currentChat.id)
        // if(data.type==1) console.log("收到群聊消息", data.id, data,  this.currentChat.id)
        let isChat = this.currentChat && this.currentChat.id===data.id && this.currentChat.type===data.type && this.$route.name==="chatting" //判断当前收到的消息是否是当前正在聊天的对象
        let isChatPage = this.$route.name==="chatting" && this.currentWeChat.currentWeChatId == data.userWechatPrimaryId  //判断收到的消息是否是当前选中的微信
        console.log("是否正在聊天",isChat)
        console.log("是否是当前聊天对象",isChatPage)
        if(isChatPage) {
          let array = this.$store.state.chatting.filter(o=>{ return o.id===data.id })
          let newData = data
          if(data.location===0) {
            newData.unreadNum = 1
            this.$store.state.hasUnreadMsg = true
          }
          if(array.length===0) {
            this.$store.state.chatting.unshift(newData)
          }else{
            this.$store.state.chatting = this.$store.state.chatting.filter(o=>{ return o.id!=data.id })
            this.$store.state.chatting.unshift(newData)
            if(isChat) {
              let obj = data
              obj.message = data.lastMessage
              obj.messageType = data.lastMessageType
              obj.senderWechatName = data.friendWechatName
              this.$store.state.history.push(obj)
              this.$store.state.toBottomRandom = Math.random()
            }
          }
        }
      }
    },

  },
}
</script>

<style lang="less">
  @import 'element-ui/lib/theme-chalk/display.css';
  @import "./style/base.less";
  @import "./style/flex.less";
  @import "./style/position.less";
  @import "./style/text.less";

  .confirmButtonClass {
    background-color: #0147fd !important;
    span {
      color: #fff !important;
    }
  }

  .el-message__closeBtn {
    color: #E6A23C !important;
  }

  .viewer-toolbar > ul > li {
    font-size: 2px !important; 
  }

  .el-radio__input.is-checked+ .el-radio__label {
    color: #0147fd !important;
    font-weight: 600;
  }

  .el-radio__input.is-checked .el-radio__inner {
    border-color: #0147fd !important;
    background: #0147fd !important;
  }
  .el-dropdown-menu {
    max-height: 60vh !important;
    overflow-y: scroll !important;
}
.el-dropdown-menu::-webkit-scrollbar {
    width: 0 !important;
    height: 0 !important;
}
.el-time-spinner__list::after, .el-time-spinner__list::before {
    height: 74px !important;
}
</style>


